package wqh.controller.json;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.socket.TextMessage;
import wqh.domain.*;
import wqh.global.GlobalSession;
import wqh.pojo.*;
import wqh.service.*;
import wqh.websocket.AlarmConver;
import wqh.websocket.alarm.AlarmSocketHandler;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by devts on 2016/9/28.
 */

@Controller
@CrossOrigin(origins = "*")
@RequestMapping("/alarm")
public class AlarmConfirmJSON {

    private Logger logger = LoggerFactory.getLogger(AlarmConfirmJSON.class);

    @Autowired
    private AlarmConfirmService alarmConfirmService;

    @Autowired
    private AlarmInCommingService alarmInCommingService;

    @Autowired
    private GeoBuildingService geoBuildingService;

    @Autowired
    private MonitorService monitorService;

    @Autowired
    private SensorService sensorService;

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private SystemLogService systemLogService;

    @Autowired
    private AlarmNoneInforService alarmNoneInforService;

    @Autowired
    private AlarmConver alarmConver;

    @Autowired
    private AlarmSocketHandler alarmSocketHandler;

    @ResponseBody
    @RequestMapping(value = "/testSocket", method = RequestMethod.GET)
    public void testSocket()
    {
        alarmSocketHandler.sendAlarmToWeb(new TextMessage("HELLO"));
    }

    @ResponseBody
    @RequestMapping(value = "/confirm", method = RequestMethod.GET)
    public Object confirm(HttpServletRequest request,@RequestParam(value = "alarm_id", required = true)int alarm_id) {
        try {
            String sessionId = request.getRequestedSessionId();
            String userName = GlobalSession.getUserNameBySessionID(sessionId);
            if(userName == null) userName = "空用户";

            AlarmInComming alarmInComming = alarmInCommingService.findAllById(alarm_id);
            if (alarmInComming == null) return MapRet.ERROR();
            alarmInCommingService.deleteRecord(alarm_id);
            Device device = deviceService.findAllByIp(alarmInComming.getIp());
            if(device == null) return MapRet.ERROR("用户信息传输装置不存在");
            Monitor monitor = monitorService.findAllByDeviceAndCode(device.getId(),String.valueOf(alarmInComming.getDev_addr())).get(0);
            if(monitor == null) return MapRet.ERROR("监测点不存在");
            AlarmConfirm alarmConfirm = new AlarmConfirm(geoBuildingService.findNameById(monitor.getGeo_level_1_id()),
                    geoBuildingService.findNameById(monitor.getGeo_level_2_id()),
                    geoBuildingService.findNameById(monitor.getGeo_level_3_id()),
                    device.getName(),
                    IPConver.int2Ip(alarmInComming.getIp()),
                    device.getPhone(),
                    sensorService.findNameByID(monitor.getSensor_id()),
                    monitor.getId(),
                    monitor.getName(),
                    alarmInComming.getDev_type(),
                    alarmInComming.getDev_addr(),
                    alarmInComming.getDev_status(),
                    (byte) 1,
                    new Long(System.currentTimeMillis() / 1000).intValue(),
                    alarmInComming.getAlarm_time());
            alarmConfirm.setUser(userName);
            alarmConfirmService.insertRecord(alarmConfirm);

            xkLog.addLog(systemLogService,"确认 "+
            alarmConfirm.getGeo_1_name() + " " +
            alarmConfirm.getGeo_2_name() + " " +
            alarmConfirm.getGeo_3_name() + " " +
            alarmConfirm.getMonitor_name() + " " +
            alarmConfirm.getDev_status(), xkLog.getAlarmConfig(), userName);

            alarmSocketHandler.cancelAlarmToWeb(alarm_id);
            System.out.println("确认");

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("确认报警信息出错：" + e);
            return MapRet.ERROR();
        }
        return MapRet.SUCCESS();
    }

/*    @ResponseBody
    @RequestMapping(value = "/ignore", method = RequestMethod.GET)
    public Object ignore(@RequestParam(value = "alarm_id", required = true) int alarm_id) {
        try {
            AlarmInComming alarmInComming = alarmInCommingService.findAllById(alarm_id);
            if (alarmInComming == null) return MapRet.ERROR();
            alarmInCommingService.deleteRecord(alarm_id);
            Monitor monitor = monitorService.findAllByCode(String.valueOf(alarmInComming.getDev_addr())).get(0);
            Device device = deviceService.findAllByID(monitor.getDevice_id());
            if(device == null) device = new Device("error",0,"error");
            AlarmConfirm alarmConfirm = new AlarmConfirm(geoBuildingService.findNameById(monitor.getGeo_level_1_id()),
                    geoBuildingService.findNameById(monitor.getGeo_level_2_id()),
                    geoBuildingService.findNameById(monitor.getGeo_level_3_id()),
                    device.getName(),
                    IPConver.int2Ip(alarmInComming.getIp()),
                    device.getPhone(),
                    sensorService.findNameByID(monitor.getSensor_id()),
                    monitor.getId(),
                    monitor.getName(),
                    alarmInComming.getDev_type(),
                    alarmInComming.getDev_addr(),
                    alarmInComming.getDev_status(),
                    (byte) 2,
                    new Long(System.currentTimeMillis() / 1000).intValue(),
                    alarmInComming.getAlarm_time());
            alarmConfirmService.insertRecord(alarmConfirm);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("忽略报警信息出错：" + e);
            return MapRet.ERROR();
        }
        return MapRet.SUCCESS();
    }*/

/*    @ResponseBody
    @RequestMapping(value = "/denial", method = RequestMethod.GET)
    public Object denial(HttpServletRequest request,@RequestParam(value = "alarm_id", required = true) int alarm_id) {
        try {
            String sessionId = request.getRequestedSessionId();
            String userName = GlobalSession.getUserNameBySessionID(sessionId);
            if(userName == null) userName = "空用户";
            AlarmInComming alarmInComming = alarmInCommingService.findAllById(alarm_id);
            if (alarmInComming == null) return MapRet.ERROR();
            alarmInCommingService.deleteRecord(alarm_id);
            Monitor monitor = monitorService.findAllByCode(String.valueOf(alarmInComming.getDev_addr())).get(0);
            Device device = deviceService.findAllByID(monitor.getDevice_id());
            if(device == null) device = new Device("error",0,"error");
            AlarmConfirm alarmConfirm = new AlarmConfirm(geoBuildingService.findNameById(monitor.getGeo_level_1_id()),
                    geoBuildingService.findNameById(monitor.getGeo_level_2_id()),
                    geoBuildingService.findNameById(monitor.getGeo_level_3_id()),
                    device.getName(),
                    IPConver.int2Ip(alarmInComming.getIp()),
                    device.getPhone(),
                    sensorService.findNameByID(monitor.getSensor_id()),
                    monitor.getId(),
                    monitor.getName(),
                    alarmInComming.getDev_type(),
                    alarmInComming.getDev_addr(),
                    alarmInComming.getDev_status(),
                    (byte) 3,
                    new Long(System.currentTimeMillis() / 1000).intValue(),
                    alarmInComming.getAlarm_time());
            alarmConfirm.setUser(userName);
            alarmConfirmService.insertRecord(alarmConfirm);

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("确认误报火警出错：" + e);
            return MapRet.ERROR();
        }
        return MapRet.SUCCESS();
    }*/

    @ResponseBody
    @RequestMapping(value = "/alarmUpdate", method = RequestMethod.GET)
    public Object confirmAll(HttpServletRequest request,@RequestParam(value = "monitor_id", required = true) int monitor_id) {
        try {
            int confirmCount = 0;
            String sessionId = request.getRequestedSessionId();
            String userName = GlobalSession.getUserNameBySessionID(sessionId);
            if(userName == null) userName = "空用户";
            List<AlarmInComming> alarmInCommingList = alarmInCommingService.findAllRecord();
            if(alarmInCommingList.size() == 0) return MapRet.ERROR("没有数据");
            for(AlarmInComming alarmInComming : alarmInCommingList){
                Device device = deviceService.findAllByIp(alarmInComming.getIp());
                if(device == null) return MapRet.ERROR("用户信息传输装置不存在");
                Monitor monitor = monitorService.findAllByDeviceAndCode(device.getId(),String.valueOf(alarmInComming.getDev_addr())).get(0);
                if(monitor == null) return MapRet.ERROR("监测点不存在");
                if(!monitor.getId().equals(monitor_id)) continue;
                AlarmConfirm alarmConfirm = new AlarmConfirm(geoBuildingService.findNameById(monitor.getGeo_level_1_id()),
                        geoBuildingService.findNameById(monitor.getGeo_level_2_id()),
                        geoBuildingService.findNameById(monitor.getGeo_level_3_id()),
                        device.getName(),
                        IPConver.int2Ip(alarmInComming.getIp()),
                        device.getPhone(),
                        sensorService.findNameByID(monitor.getSensor_id()),
                        monitor.getId(),
                        monitor.getName(),
                        alarmInComming.getDev_type(),
                        alarmInComming.getDev_addr(),
                        alarmInComming.getDev_status(),
                        (byte) 1,
                        new Long(System.currentTimeMillis() / 1000).intValue(),
                        alarmInComming.getAlarm_time());
                alarmConfirm.setUser(userName);
                alarmConfirmService.insertRecord(alarmConfirm);
                alarmInCommingService.deleteRecord(alarmInComming.getId());
                xkLog.addLog(systemLogService,"确认 "+
                        alarmConfirm.getGeo_1_name() + " " +
                        alarmConfirm.getGeo_2_name() + " " +
                        alarmConfirm.getGeo_3_name() + " " +
                        alarmConfirm.getMonitor_name() + " " +
                        alarmConfirm.getDev_status(), xkLog.getAlarmConfig(), userName);
                confirmCount++;
            }
            return MapRet.DATA("成功确认" + confirmCount + "条记录");
        } catch (Exception e) {
            e.printStackTrace();
            return MapRet.SQL_ERROR();
        }
    }

/*    @ResponseBody
    @RequestMapping(value = "/alarmUpdate2", method = RequestMethod.GET)
    public Object changeStatus2(@RequestParam(value = "alarm_id", required = true) int alarm_id) {
        try {
            alarmConfirmService.updateConfirmStatus(3, new Long(System.currentTimeMillis() / 1000).intValue(), alarm_id);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("更新报警状态出错2：" + e);
            return MapRet.SQL_UPDATE_ERROR();
        }
        return MapRet.SQL_UPDATE_SUCCESS();
    }*/


    @ResponseBody
    @RequestMapping(value = "/getConfirmData", method = RequestMethod.GET)
    public Object getAllConfirm(@RequestParam(value = "draw",required = true) int draw,
                                @RequestParam(value = "start",required = true) int start,
                                @RequestParam(value = "length",required = true) int length
//                                @RequestParam(value = "order[0][column]",required = true) int column,
//                                @RequestParam(value = "order[0][dir]",required = true) String order,
//                                @RequestParam(value = "search[value]",required = true) String search
    )
    {
        PageHelper.startPage(start / length + 1, length);
        List<AlarmConfirm> alarmConfirmList = alarmConfirmService.findByStatus("火警");
        int count = alarmConfirmService.findAllCount("火警");
        @SuppressWarnings("unchecked")
        PageInfo page = new PageInfo(alarmConfirmList);
        return MapRet.DATATABLES(draw,count,new Long(page.getTotal()).intValue(),alarmConfirmList);
    }

    @ResponseBody
    @RequestMapping(value = "/getNoneConfirmData", method = RequestMethod.GET)
    public Object getAllNoneConfirm()
    {
        return alarmConver.getAllStatus("火警");
    }

    @ResponseBody
    @RequestMapping(value = "/getConfirmFaultData", method = RequestMethod.GET)
    public Object getAllConfirmFault(@RequestParam(value = "draw",required = true) int draw,
                                @RequestParam(value = "start",required = true) int start,
                                @RequestParam(value = "length",required = true) int length
    )
    {
        PageHelper.startPage(start / length + 1, length);
        List<AlarmConfirm> alarmConfirmList = alarmConfirmService.findByStatus("故障");
        int count = alarmConfirmService.findAllCount("故障");
        @SuppressWarnings("unchecked")
        PageInfo page = new PageInfo(alarmConfirmList);
        return MapRet.DATATABLES(draw,count,new Long(page.getTotal()).intValue(),alarmConfirmList);
    }

    @ResponseBody
    @RequestMapping(value = "/getNoneConfirmFaultData", method = RequestMethod.GET)
    public Object getAllNoneConfirmFault()
    {
        return alarmConver.getAllStatus("故障");
    }

    @ResponseBody
    @RequestMapping(value = "/getConfirmFalseData", method = RequestMethod.GET)
    public Object getAllConfirmFalse(@RequestParam(value = "draw",required = true) int draw,
                                     @RequestParam(value = "start",required = true) int start,
                                     @RequestParam(value = "length",required = true) int length
    )
    {
        PageHelper.startPage(start / length + 1, length);
        List<AlarmConfirm> alarmConfirmList = alarmConfirmService.findByStatus("误报");
        int count = alarmConfirmService.findAllCount("误报");
        @SuppressWarnings("unchecked")
        PageInfo page = new PageInfo(alarmConfirmList);
        return MapRet.DATATABLES(draw,count,new Long(page.getTotal()).intValue(),alarmConfirmList);
    }

    @ResponseBody
    @RequestMapping(value = "/getNoneConfirmFalseData", method = RequestMethod.GET)
    public Object getAllNoneConfirmFalse()
    {
        return alarmConver.getAllStatus("误报");
    }

    @ResponseBody
    @RequestMapping(value = "/getAllIgnore", method = RequestMethod.GET)
    public Object getAllIgnore() {
        List<AlarmIncommingPojo> alarmIncommingPojoList = new ArrayList<AlarmIncommingPojo>();
        List<AlarmInComming> alarmInCommingList = alarmInCommingService.findAllRecord();
        if(alarmInCommingList.size() == 0)  return MapRet.DATA(alarmIncommingPojoList);
        for(AlarmInComming a : alarmInCommingList){
            Device device = deviceService.findAllByIp(a.getIp());
            if(device == null) continue;
            Monitor monitor = monitorService.findAllByDeviceAndCode(device.getId(),String.valueOf(a.getDev_addr())).get(0);
            if(monitor == null) continue;
            String area = geoBuildingService.findNameById(monitor.getGeo_level_1_id());
            String building = geoBuildingService.findNameById(monitor.getGeo_level_2_id());
            String floor = geoBuildingService.findNameById(monitor.getGeo_level_3_id());
            String sensor = sensorService.findNameByID(monitor.getSensor_id());
            alarmIncommingPojoList.add(new AlarmIncommingPojo(
                    a,device,monitor,area,building,floor,sensor
            ));
        }
        return MapRet.DATA(alarmIncommingPojoList);
    }

    @ResponseBody
    @RequestMapping(value = "/getOneMonthAll", method = RequestMethod.GET)
    public Object getOneMonthAll() {
        Integer objTime = new Long(System.currentTimeMillis() / 1000).intValue() - 2592000;
        List<AlarmConfirm> alarmConfirmList = alarmConfirmService.findAllByTimeTo(objTime);
        return MapRet.DATA2(alarmConfirmList.size(),alarmConfirmList);
    }

    @ResponseBody
    @RequestMapping(value = "/getAllIgnoreCount", method = RequestMethod.GET)
    public Object getOneMonthIgnore()
    {
        return MapRet.DATA2(alarmInCommingService.countAll(),null);
    }

    @ResponseBody
    @RequestMapping(value = "/unHandler",method = RequestMethod.GET)
    public Object unHandler()
    {
        List<MonitorAlarm> monitorAlarmList = new ArrayList<MonitorAlarm>();
        List<AlarmInComming> alarmInCommingList = alarmInCommingService.findAllRecord();
        for(AlarmInComming a : alarmInCommingList)
        {
            String code = String.valueOf(a.getDev_addr());
            List<Monitor> monitorList = monitorService.findAllByCode(code);
            if(monitorList.size() == 0)
            {
                AlarmNoneInfor alarmNoneInfor = new AlarmNoneInfor(IPConver.int2Ip(a.getIp()),
                        a.getDev_type(),
                        a.getDev_addr(),
                        a.getDev_status(),
                        a.getAlarm_time(),
                        a.getConfirm_status());
                alarmInCommingService.deleteRecord(a.getId());
                alarmNoneInforService.insertRecord(alarmNoneInfor);
                continue;
            }
            Monitor monitor = monitorList.get(0);
            GeoBuilding geoBuilding1 = geoBuildingService.findRecordById(monitor.getGeo_level_1_id());
            GeoBuilding geoBuilding2 = geoBuildingService.findRecordById(monitor.getGeo_level_2_id());
            GeoBuilding geoBuilding3 = geoBuildingService.findRecordById(monitor.getGeo_level_3_id());
            Device device = deviceService.findAllByID(monitor.getDevice_id());
            Sensor sensor = sensorService.findAllByID(monitor.getSensor_id());
            monitorAlarmList.add(new MonitorAlarm(monitor,geoBuilding1,geoBuilding2,geoBuilding3,device,sensor,a));
        }
        return MapRet.ALARM_DATAS(monitorAlarmList);
    }

    @ResponseBody
    @RequestMapping(value = "/unHandler2",method = RequestMethod.GET)
    public Object unHandler2()
    {
        Map<String,Integer> map = new HashMap<String, Integer>();
        map.put("alarmLogCount",alarmInCommingService.countAllStatus("火警"));
        map.put("sensorError",alarmInCommingService.countAllStatus("故障"));
        map.put("falseAlarmLogCount",alarmInCommingService.countAllStatus("误报"));
        return MapRet.DATA(map);
    }

    @ResponseBody
    @RequestMapping(value = "/deleteById",method = RequestMethod.GET)
    public Object deleteById(HttpServletRequest request,@RequestParam(value = "id",required = true) int id)
    {
        try {
            String sessionId = request.getRequestedSessionId();
            String userName = GlobalSession.getUserNameBySessionID(sessionId);
            if(userName == null) userName = "空用户";
            AlarmConfirm alarmConfirm = alarmConfirmService.findAllById(id);
            if(alarmConfirm != null){
                xkLog.addLog(systemLogService,"删除 "+
                        alarmConfirm.getGeo_1_name() + " " +
                        alarmConfirm.getGeo_2_name() + " " +
                        alarmConfirm.getGeo_3_name() + " " +
                        alarmConfirm.getMonitor_name() + " " +
                        alarmConfirm.getDev_status(), xkLog.getAlarmConfig(), userName);
                alarmConfirmService.deleteById(id);
            }
            return MapRet.SQL_DELETE_SUCCESS();
        }catch (Exception e){
            e.printStackTrace();
            return MapRet.SQL_DELETE_ERROR();
        }
    }

    @ResponseBody
    @RequestMapping(value = "/getCount",method = RequestMethod.GET)
    public Object getCount()
    {
        int alarm = alarmInCommingService.countAllStatus("火警");
        int fault = alarmInCommingService.countAllStatus("故障");
        int falseAlarm = alarmInCommingService.countAllStatus("误报");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("fireLog",alarm);
        map.put("faultLog",fault);
        map.put("falseLog",falseAlarm);
        map.put("totalLog",alarm + falseAlarm + fault);
        return MapRet.DATA(map);
    }

}
